import { Injectable } from '@nestjs/common'
import { CreateAccountDto } from './dto/create-account.dto'
import { UpdateAccountDto } from './dto/update-account.dto'
import { PrismaService } from '../prisma/prisma.service'

@Injectable()
export class AccountService {
    constructor(private readonly prisma: PrismaService) { }

    create(createAccountDto: CreateAccountDto) {
        return this.prisma.account.create({
            data: createAccountDto
        })
    }

    async findAll(query: { tel?: string, status?: number, pageIndex: number, pageSize: number }) {
        const list = await this.prisma.account.findMany({
            where: {
                tel: { contains: query.tel },
                status: query.status
            },
            skip: (query.pageIndex - 1) * query.pageSize,
            take: query.pageSize
        })
        const total = await this.prisma.account.count({
            where: {
                tel: query.tel,
                status: query.status
            }
        })
        return { list, total }
    }

    findOne(id: number) {
        return this.prisma.account.findUnique({
            where: { id }
        })
    }

    update(id: number, updateAccountDto: UpdateAccountDto) {
        return this.prisma.account.update({
            where: { id },
            data: updateAccountDto
        })
    }

    remove(id: number) {
        return this.prisma.account.delete({
            where: { id }
        })
    }

	async updatePassword(params: {tel: string, oldPassword: string, newPassword: string}) {
		
		const account = await this.prisma.account.findUnique({
			where: { tel: params.tel }
		})
		if (params.oldPassword !== account.password) {
			return {
				code: '1004',
                tips: '哦豁，原密码不正确，你不会是混子吧！',
                data: null
			}
		} else {
			return this.prisma.account.update({
				where: { tel: params.tel },
				data: { password: params.newPassword }
			})
		}
	}
}
